package com.urfresh.sp.user.schedule.configure;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;

import java.util.Arrays;

@Configuration
public class MongoConfig {

    Logger logger = LoggerFactory.getLogger(MongoConfig.class);

    @Value("${mongoUrl}")
    String mongoUrl;
    @Value("${mongoPort}")
    int mongoPort;
    @Value("${mongoAuthName}")
    private String mongoAuthName;
    @Value("${mongoDbName}")
    private String mongoDbName;
    @Value("${mongoAuthPassword}")
    private String mongoAuthPassword;


    /*
	 * Factory bean that creates the com.mongodb.Mongo instance
	 */
    @Bean
    public MongoClient mongClient() throws Exception {
        MongoClient client = new MongoClient(
                Arrays.asList(
                        new ServerAddress(mongoUrl, mongoPort)),
                Arrays.asList(
                        MongoCredential.createCredential(mongoAuthName, mongoDbName, mongoAuthPassword.toCharArray())
                ),
                MongoClientOptions.builder()
                        .socketKeepAlive(true)  //是否保持长链接
                        .connectionsPerHost(200) // 最大连接数
                        .minConnectionsPerHost(10)// 最小连接数
                        .build());
        return client;
    }

    @Bean
    public SimpleMongoDbFactory mongoFactory() throws Exception {
        return new SimpleMongoDbFactory(mongClient(), mongoDbName);
    }

    @Bean
    public MongoTemplate mongoTemplate() throws Exception {
        return new MongoTemplate(mongoFactory());
    }


}
